<template>
<!-- 
uniap Appid = __UNI__F9A4593  adpid=1676059109
uniap Appid = __UNI__D4B0056  adpid=1304062947
 
 -->	
	<ad-rewarded-video ref="adRewardedVideo" adpid="1304062947" :preload="false" :loadnext="false" :disabled="true"
		:url-callback="callBack" v-slot:default="{loading, error}" @load="onadload" @close="onadclose"
		@error="onaderror">
		<u-toast ref="uToast"></u-toast>

		<view class="content" style="padding: 2rem;">
			<u-modal :show="showModel" title="帮助" content="内容" @close="showModel=false;" :closeOnClickOverlay="true"
				:showConfirmButton="true" confirmText="知道了" @confirm="showModel = false;">
				<v-slot>
					<view class="slot-content" style="color: #333;">
						<rich-text :nodes="content"></rich-text>
					</view>
				</v-slot>
			</u-modal>
			<view class="content_help" @click="showModel = true">
				<u--text align="right" text="帮助" size="20px" color="#fff" :iconStyle="{width:'20px',height:'20px'}"
					suffixIcon="https://file.ruyicult.com/Rscsgo/images/web/common/help_active.png"></u--text>
			</view>
			<view class="content_view">
				<!-- <u-count-down v-if="isLoading" @finish="countDownFn" :time="timeData2" format="DD:HH:mm:ss"
					autoStart millisecond @change="onChange">
					<view class="time">
						<text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
						<text class="time__item">{{ timeData.seconds }}&nbsp;秒后可再次观看</text>
					</view>
				</u-count-down> -->
				<!-- <view class="time">
					<text class="time__item">
						用户id：{{callBack.userId}}
					</text>
				</view>
				<view class="time">
					<text class="time__item">
						用户extra：{{callBack.extra}}
					</text>
				</view>
				<view class="time">
					<text class="time__item">
						用户sign：{{callBack.sign}}
					</text>
				</view> -->
				<view class="u-flex-xy-center">
					<button type="primary" style="background:#f5c362;" :disabled="isLoading" :loading="isLoading"
						@click="showAd">{{`观看广告获得奖励`}}</button>
					<!-- 测试用 -->
					<!-- <button type="primary" style="background:#f5c362;" @click="showAd">{{`观看广告获得奖励`}}</button> -->
				</view>
			</view>

		</view>

	</ad-rewarded-video>

</template>

<script>
	import {
		sendUnad
	} from "@/api/user.js";
	// 引入 js-md5 库
	import md5 from 'js-md5';
	import Utils from "@/common/utils.js"
import cellGroup from "../../uni_modules/uview-ui/libs/config/props/cellGroup";
	export default {
		data() {
			return {
				timeDelay:5 * 60 * 1000,//固定值不可更改
				timeOut: undefined,
				timeData2: 5 * 60 * 1000,//观看间隔时长
				timeData: {},//用来记录回显
				signKey: "1wedsacjneijwie",
				showModel: false,
				content: `
				<p>1、每次观看广告都会获得特定奖励，实时到账；</p>
				<p>2、每周一，会根据上周贡献数据自动发放累计奖励；</p>
				<p>注意：短时间频繁，单IP多设备、无卡新设备、对广告内容无任何点击，都会影响到您的实时收益和每周收益。</p>
				`,
				isLoading: false,
				callBack: {
					userId: 0,
					extra: "",
					sign: "",
				},
				countKey: '',//今日观看次数
				timeKey: "",//间隔时间戳得键
			}
		},
		onLoad(options) {
			const date = new Date();
			// 今日观看次数
			this.countKey = `${Utils.formatDate(date)}-count`;
			const count = uni.getStorageSync(this.countKey);
			console.log("观看次数:",count);
			if (options && options.userId) {
				this.callBack.userId = options.userId;
				this.init();
			}

		},
		// 当页面销毁得时候记录当前剩余时间
		onUnload() {
			// const date = new Date();
			// const currentDate = date.getTime();
			// // 如果退出得时候时间间隔还有剩余，存入存入。
			// // console.log(this.timeData.seconds>0,"页面销毁");
			// if(this.timeData.seconds>0){
			// 	let {minutes,seconds}=this.timeData;
			// 	this.timeData2 = (minutes*60+seconds)*1000;
			// 	uni.setStorageSync(this.timeKey,this.timeData2);
			// 	console.log("剩余间隔毫秒：",this.timeData2);
			// }
		},
		// 当页面开始准备时
		onReady() {
			this.isLoading = true;
			this.$refs.adRewardedVideo.load();
			uni.setStorageSync(this.timeKey,'')
		},
		methods: {
			// 初始化查询接口参数
			init() {
				const currentDate = new Date();
				const currentTimestamp = currentDate.getTime();
				let random = Math.floor(Math.random() * 900000) + 100000;
				this.callBack.extra = `${this.callBack.userId}ad${currentTimestamp}${random}`;
				this.callBack.sign = md5(this.callBack.userId + this.callBack.extra + this.signKey);
			},
			// 开始看广告
			showAd() {
				let count = uni.getStorageSync(this.countKey);
				if (count >= 30) {
					return this.showToast("今日观看次数已达上限，请明日再来", 'error');
				}
				this.isLoading = true;
				// 模拟流程
				// setTimeout(()=>{
				// 	let countEd = uni.getStorageSync(this.countKey);
				// 	countEd++;
				// 	uni.setStorageSync(this.countKey, countEd);
				// 	this.init();
				// 	this.timeData2 = this.timeDelay;
				// },this.timeData2)
				// 开始看广告
				this.$refs.adRewardedVideo.show();
			},
			// 广告准备就绪
			onadload(e) {
				// this.setDely();
				this.cannel();
			},
			// 用户点击关闭
			onadclose(e) {
				const detail = e.detail
				console.log(detail,"detail");
				// 用户点击了【关闭广告】按钮
				if (detail && detail.isEnded) {
					this.isLoading = true;
					// 		// 正常播放结束
					// 		// 这里应该联网给予用户激励。且这段代码应该做安全保护，详见下文中的“安全注意”
					sendUnad({
						extra: this.callBack.extra,
						userId: this.callBack.userId,
						sign: this.callBack.sign,
					}).then((res) => {
						let {
							amount,
							moniAmount
						} = res.data;
						this.showToast(`恭喜获得${amount}如意币，${moniAmount}模拟币!`, 'success');
						let countEd = uni.getStorageSync(this.countKey);
						countEd++;
						// 设置观看次数
						uni.setStorageSync(this.countKey, countEd);
						this.init();
						this.cannel();
						// this.timeData2 = this.timeDelay;
			
					}).catch(({
						msg
					}) => {
						console.log(msg);
						this.showToast(`退出太快/频繁，请稍后再试哦！`, 'error');
						this.cannel();
					})
			
				} else {
					this.showToast("退出太快/频繁，请稍后再试哦！", 'error');
					this.cannel();
				}
			},
			// 广告组件错误
			onaderror(e) {
				let {
					code,
					errMsg
				} = e.detail;
				console.log(code,errMsg,"哈哈哈哈哈");
				this.showToast(`广告频繁请稍后再试哦！`, 'error');
				// this.setDely();
				this.cannel();
			},
			// 倒计时更改时间
			onChange(e) {
				this.timeData = e;
			},
			countDownFn(){
				this.isLoading=false;
				this.timeData2 = this.timeDelay;
			},
			// 显示提示语
			showToast(msg, type) {
				this.$refs.uToast.show({
					type: type,
					message: msg,
					position: 'top',
				});
			},
			// 取消观看，销毁计时器
			cannel() {
				this.isLoading = false;
				if (this.timeOut) {
					clearTimeout(this.timeOut);
				}
			},
			// 判断剩余时间
			// setDely(){
			// 	const date = new Date();
			// 	// 今日间隔市场
			// 	this.timeKey = `${Utils.formatDate(date)}-time`;
			// 	const time_1 = uni.getStorageSync(this.timeKey);
			// 	console.log(time_1,"间隔时间",time_1 == ' ');
			// 	// 如果时间间隔为空，那么设置初始值，并解冻观看按钮
			// 	if (time_1 == ' ') {
			// 		this.timeData2 = this.timeDelay;
			// 		this.cannel();
			// 	} else {
			// 		// 如果有间隔时间，计算当前时间戳与本地时间戳间隔，如果小于5分钟，设置时间间隔
			// 		console.log("剩余间隔时间",Number(time_1));
			// 		if (Number(time_1) <= this.timeDelay) {
			// 			this.timeData2 = Number(time_1);
			// 			this.isLoading = true;
			// 		}
			// 	}
			// },
			
		}
	}
</script>
<style lang="scss">
	.content {

		background: url("@/static/image/assBg.jpg") center center / 100% 100%;
		position: relative;
		height: 100vh;
		color: #fff;

		.content_help {
			display: flex;
			flex-direction: row;
			justify-content: end;
			align-items: end;
			gap: 5rpx;
		}

		.time {
			@include flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 10px;

			&__item {
				color: #fff;
				font-size: 20px;
				text-align: center;
			}
		}

		.content_view {
			width: 100%;
			position: absolute;
			bottom: 20vh;
			left: 0;
		}
	}
</style>